import urllib

from django import template
from django.template import Node, NodeList, Template, Context, Variable, VariableDoesNotExist
from django.template.defaulttags import IfEqualNode
from django.template.loader import render_to_string
from django.contrib.contenttypes.models import ContentType

from django_utils.templatetag_helpers import resolve_variable, copy_context
import tagging.models

register = template.Library()
    
@register.tag(name="tagged_content_row")
def do_tagged_content_row(parser,  token):
    try:
        tag, content, template = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError,  "%r tag requires two arguments" % token.contents.split()[0]
    return TaggedContentRow(content, template)

class TaggedContentRow(template.Node):
    """
    @content
    """
    def __init__(self,  content, template):
        self.content = content
        self.template = template
        
    def render(self,  context):
        content = resolve_variable(self.content,  context,  None)
        template = resolve_variable(self.template, context, self.template)
        new_context = copy_context(context)
        
        new_context['node'] = content
        new_context['object'] = content
        
        return render_to_string(template,  {},  context)
 
@register.tag(name="related_tags") 
def do_related_object_tags(parser,  token):
    try:
        tag, object = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError,  "%r tag requires one argument" % token.contents.split()[0]
    return RelatedTags(object)

class RelatedTags(template.Node):
    """
    @object
    """
    def __init__(self,  object):
        self.object = object
    
    def render(self,  context):
        object = resolve_variable(self.object,  context,  None)
        content_type_object = ContentType.objects.get_for_model(object.__class__)
        tags = object.get_tags_with_count()
        
        context['object'],  context['tags'],  context['content_type'] = object,  tags,  content_type_object.id
        return render_to_string('sidebar/related_tags.html',  {},  context)

@register.tag(name="associated_tags") 
def do_associated_tags(parser,  token):
    try:
        tag, tag_name = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError,  "%r tag requires one argument" % token.contents.split()[0]
    return AssociatedTags(tag_name)

class AssociatedTags(template.Node):
    """
    @object
    """
    def __init__(self,  tag):
        self.tag = tag
    
    def render(self,  context):
        tag = urllib.unquote(resolve_variable(self.tag,  context,  None))
        associated_tags = NodeWithTags.get_associated_tags(tag)
        
        context['tags'] = associated_tags
        return render_to_string('sidebar/associated_tags.html',  {},  context)

@register.tag(name='active_tags')
def do_most_active_tags(parser, token):
    try:
        tag, content_type, _as, context_variable = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError,  "%r tag requires three arguments" % token.contents.split()[0]
    return ActiveTags(content_type, context_variable)

class ActiveTags(template.Node):
    """
    @tag_name
    @content_type
    """
    def __init__(self, content_type, context_variable):
        self.content_type = content_type
        self.context_variable = context_variable
    
    def render(self,  context):
        content_type = resolve_variable(self.content_type, context, self.content_type)
        
        try:
            content_type_object = ContentType.objects.get(id = int(content_type))
        except ValueError:
            content_type_object = None
        except ObjectDoesNotExist:
            content_type_object = None
            
        if content_type_object:
            most_active_tags = tagging.models.Tag.meta_objects.most_active(content_type_object.id, 5)
        else:
            most_active_tags = []
        
        context[self.context_variable] = most_active_tags
        return ''